package gew.beans;

import gew.metadata.CustomSql;
import gew.services.DimensionValueService;
import gew.utils.SqlUtils;
import java.util.ArrayList;
import java.util.Enumeration;
import javax.ejb.EJB;
import javax.faces.bean.RequestScoped;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RequestScoped
public class BaseBean {

    @EJB
    DataFacade2 df;

    @EJB
    DimensionValueService dvs;

    void logRequest(final HttpServletRequest r, final String section, final String requestURI) {
        Enumeration<String> pEnum = r.getHeaderNames();
        ArrayList<String> headerNames = new ArrayList<>();
        while (pEnum.hasMoreElements()) {
            headerNames.add(pEnum.nextElement());
        }
        ArrayList<String> headerValues = new ArrayList<>();
        for (String header : headerNames) {
            headerValues.add(r.getHeader(header));
        }
        HttpSession s = r.getSession();
        String sessionId = s == null ? SqlUtils.EMPTY : s.getId();
        ArrayList<String> stmts = new ArrayList<>();
        
        String q1 = CustomSql.getLogRequest(section, sessionId,
                s == null ? 0 : s.getCreationTime(),
                s == null ? 0 : s.getLastAccessedTime(),
                s == null ? true : s.isNew(),
                r.getCharacterEncoding(), r.getLocalAddr(),
                r.getLocalName(), r.getLocalPort(), r.getLocale(),
                r.getProtocol(), r.getRemoteAddr(), r.getRemoteHost(),
                r.getRemotePort(), r.getRemoteUser(), requestURI,
                r.getRequestedSessionId(), r.getScheme(), r.getServerName(),
                r.getServerPort(), r.getServletPath());
        String[] arr = q1.split(SqlUtils.SEMICOLON);
            for (int i = 0; i < arr.length; i++) {
                if (!SqlUtils.EMPTY.equals(arr[i])){
                    stmts.add(arr[i]);
                }
            }
        for (int i = 0; i < Math.min(headerNames.size(), headerValues.size()); i++) {
            stmts.add(CustomSql.getLogHeader(sessionId, headerNames.get(i), headerValues.get(i)));
        }
        Cookie[] cookies = r.getCookies();
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                stmts.add(CustomSql.getLogCookie(sessionId, cookies[i].getName(), cookies[i].getValue()));
            }
        }
        df.logRequest(stmts);
    }

}
